<?php

namespace Home\Controller;

use Think\Controller;
use Think\Template\Driver\Mobile;
use Model\usersModel;
use Admin\Controller\UsersController;

class AccountController extends Controller {
    function __destruct(){                                                                         // 析构方法  写入用户访问和操作日志
       // require '/home/wwwroot/default/world/behavior.php';
    	require 'behavior.php';
    }
	// 判断用户名和邮箱是否相等 --- 陈柏村
	public function checkUserEmail($username, $email) {
		$usersModel = new \Model\usersModel ();
		
		$checkResults = $usersModel->query ( "select * from users where (username = '$username' and email = '$email')" );
		
		if ($checkResults != null) {
			return 1;
		} else {
			return 0;
		}
	}
	
	// 判断用户名是否被使用 -- 陈柏村
	public function checkName($id) {
		$userModel = new \Model\usersModel ();
		
		echo $checkInfo = $userModel->checkName ( $id );
		return $checkInfo;
	}
	
	// 判断用户原密码是否正确
	public function checkPwd() {
		$userModel = new \Model\usersModel ();
		$id = $_REQUEST ['id']; // 获取传过来的值
		$result = $userModel->checkPwd ( $id ); // 返回标志值：0即为原密码正确，其余则为错误
		echo $result; // 返回调用值
	}
	
	// 注销 -- 陈柏村
	public function Logout() {
		$Hint = new \Operation\Controller\HintController (); // 实例化Hint
		
		session ( null );
		$Hint->mysuccee ( "已退出 正在返回首页", '1', 'Home/Index/index' );
	}
	
	// 忘记密码下一步
	public function setBack() {
		$Hint = new \Operation\Controller\HintController ();
		$users = new \Model\usersModel (); // 实例化users
		$username = $_REQUEST ['un'];
		$user = $users->where ( "username = '$username'" )->select ();
		
		if (! empty ( $_POST )) {
			$password = $_POST ['password'];
			$password2 = $_POST ['password2'];
			if ($_POST ['rand'] == null) {
			    $Hint->myerror ( "校验码不能为空！" );
			    die ();
			}
			if ($_POST ['rand'] != $user [0] ['rand']) {
				$Hint->myerror ( "校验码错误！" );
				die ();
			}
			
			if ($password == null || $password2 == null) {
				$Hint->myerror ( "新密码不能为空！" );
				die ();
			}
			
			if (strlen ( $password ) < 6) {
				$Hint->myerror ( "密码不能少于6位！" );
				die ();
			}
			
			if ($password != $password2) {
				$Hint->myerror ( "两次密码输入不一致！" );
				die ();
			}
			
			$data ['pwd'] = MD5 ( $password );
			$data ['rand'] = null;
			$resuts = $users->where ( "username = '$username'" )->save ( $data );
			if ($resuts) {
				$Hint->mysuccee ( "恭喜:修改成功!", 1, "Home/Account/Login" );
				die ();
			} else {
				$Hint->myerror ( "对不起,修改失败!", 1 );
				die ();
			}
		} else {
			$this->assign ( 'user', $user );
			$this->display ();
		}
	}
	
	// 忘记密码
	public function Back() {
		$Hint = new \Operation\Controller\HintController ();
		$users = new \Model\usersModel (); // 实例化users
		
		if (! empty ( $_POST )) {
			
			// 判断用户名和邮箱是否相等
			$username = I ( 'post.username' );
			$email = I ( 'post.email' );

			$checkResults = $this->checkUserEmail ( "$username", "$email" );
			
			if ($checkResults != 1) {
				$Hint->myerror ( "用户名和邮箱不匹配,请检查!" );
				die ();
			} else {
				$title = "找回密码通知！";
				$srand = rand ( 11111, 99999 );
				$data ['rand'] = $srand;
				$users->where ( "username = '$username'" )->save ( $data ); // 更新数据库
				$content = "校验码:$srand";
				if (SendMail ( $email, $title, $content )) {
					$Hint->mysuccee ( "发送成功,请到邮箱查看校验码!", 2, "Home/Account/setBack/un/$username" );
					die ();
				} else {
					$Hint->myerror ( "发送失败!", 1 );
					die ();
				}
			}
		}
		$this->display ();
	}
	
	// 修改密码
	public function editPswd() {
		$Hint = new \Operation\Controller\HintController ();
		$users = new \Model\usersModel ();
		$uid = session ( 'userUid' ); // 取出用户uid
		if (! empty ( $_POST )) {
			
			$password = $_POST ['password'];
			$password_new = $_POST ['password_new'];
			$password_new_ok = $_POST ['password_new_ok'];
			
			if ($password == null) {
				$Hint->myerror ( "原密码不能为空" );
				die ();
			}
			
			if ($password_new == null) {
				$Hint->myerror ( "新密码不能为空" );
				die ();
			}
			
			if ($password_new_ok == null) {
				$Hint->myerror ( "新密码不能为空" );
				die ();
			}
			
			if (strlen ( $password_new_ok ) < 6) {
				$Hint->myerror ( "密码不能少于6位" );
				die ();
			}
			
			if ($password_new != $password_new_ok) {
				$Hint->myerror ( "两次密码输入不一致" );
				die ();
			}
			
			// 比对旧密码
			$oldPassword = $users->where ( "uid = $uid" )->getField ( 'pwd' ); // 获取该学生密码，用作比对输入的旧密码是否正确，拿到的值即原密码
			
			if ($oldPassword != MD5 ( $password )) {
				$Hint->myerror ( "原密码错误!" );
				die ();
			}
			
			if ($oldPassword == MD5 ( $password_new_ok )) {
				$Hint->myerror ( "新密码不能和老密码相同" );
				die ();
			}
			
			// 验证通过 修改密码
			$userInfo ['pwd'] = MD5 ( $password_new_ok );
			$userInfo ['Token'] = base64_encode ( $_POST ['password_new_ok'] );
			$resuts = $users->where ( "uid=$uid" )->save ( $userInfo );
			
			if ($resuts != null) {
				$Hint->mysuccee ( "恭喜:修改成功!", 1, "Home/Index/index" );
				die ();
			} else {
				$Hint->myerror ( "对不起,修改失败!", 2 );
				die ();
			}
		}
		
		$this->display ();
	}
	
	// 修改个人信息
	public function editInfo() {
		$Hint = new \Operation\Controller\HintController (); // 实例化Hint
		$Hint->checkLogin ( 1 ); // 验证学生是否登陆
		
		$editInfo = new \Model\usersModel (); // 实例化users
		$uid = session ( 'userUid' ); // session取uid
		
		if (! empty ( $_POST )) {
			if (null != $_FILES ['photo'] ['name']) { // 判断文件是否被修改，如果为空则不调用upload方法
				$filename = $editInfo->where ( "uid=$uid" )->getField ( 'photo' ); // 从数据库中取出头像名
				$file = './Public/UPLOADS/photo/' . "$filename"; // 把目录名存到file中
				if (strlen ( $filename ) > 20) { // 默认头像路径strlen小于等于20，不能删除默认头像
					unlink ( $file ); // 删除真实数据
				}
				
				$image = new \Think\Image (); // 实例化Image
				$info = $Hint->upload ( 'photo' ); // 调用upload方法
				$photoname = $info ['photo'] ['savepath'] . $info ['photo'] ['savename']; // 存储附件的子目录和名
				$image->open ( './Public/UPLOADS/photo/' . "$photoname" ); // 打开原头像
				$image->thumb ( 200, 200, \Think\Image::IMAGE_THUMB_FIXED )->save ( './Public/UPLOADS/photo/' . "$photoname" ); // 按照原图的比例生成一个最大为200*200的缩略图并保存
				$date ['photo'] = $photoname; // 把附件的名存储到photo字段
			}
			
			$date ['realname'] = $_POST ['realname']; // 取真实姓名
			$date ['phone'] = $_POST ['phone']; // 取电话号
			$date ['email'] = $_POST ['email']; // 取email
			$date ['intro'] = $_POST ['intro']; // 取个人介绍
			
			$result = $editInfo->where ( "uid=$uid" )->save ( $date ); // 更新数据库
			if ($result) {
				// 修改完用户名后更新session
				session ( 'userRealname', $_POST ['realname'] );
				session ( 'userPhoto', $_POST ['photo'] . $photoname );
				$Hint->mysuccee ( "修改成功！", "1", "Home/Index/index" ); // 修改成功跳回首页
				die ();
			} else {
				if ($errorInfo == null) {
					$errorInfo = "没有信息被修改";
				}
				$Hint->myerror ( $errorInfo, "2" );
				die ();
			}
		} else {
			$userInfo = $editInfo->where ( "uid=$uid" )->select (); // 查询用户原有数据
			$this->assign ( 'photo', $photoname );
			$this->assign ( 'userInfo', $userInfo );
			$this->display ();
		}
	}
	
	/*// 用户注册模块
	public function Registered() {
		session ( null ); // 清空session
		if (! empty ( $_POST )) {
			session ( null ); // 清空session
			$Hint = new \Operation\Controller\HintController (); // 实例化Hint
			$usersmodel = M ( 'users' ); // 实例化users
			$image = new \Think\Image (); // 实例化Image
			
			if (null != $_FILES ['photo'] ['name']) { // 判断文件是否被修改，如果为空则不调用upload方法
				$info = $Hint->upload ( 'photo' ); // 调用upload方法
				$photoname = $info ['photo'] ['savepath'] . $info ['photo'] ['savename']; // 存储头像的子目录和名字
				$image->open ( './Public/UPLOADS/photo/' . "$photoname" ); // 打开原头像
				$image->thumb ( 200, 200, \Think\Image::IMAGE_THUMB_FIXED )->save ( './Public/UPLOADS/photo/' . "$photoname" ); // 按照原图的比例生成一个最大为200*200的缩略图并保存
			} else {
				$photoname = $Hint->randPhoto (); // 随机给个头像
			}
			
			$username = $_POST ['username']; // 取出账户名
			$password1 = $_POST ['password']; // 取出密码
			$password2 = $_POST ['password_ok']; // 取出确认密码
			$stunum = $_POST ['stunum']; // 学号
			$realname = $_POST ['realname']; // 真实姓名
			$email = $_POST ['email']; // email
			$phone = $_POST ['phone']; // 电话号
			$intro = $_POST ['intro']; // 个人介绍
			
			if ($password1 !== $password2) {
				$Hint->myerror ( "两次密码输入不一致！", "2" );
				die ();
			}
			if (false == (strlen ( $password1 ) > 5 && strlen ( $username ) > 2)) { // 验证账户和密码是否过于简单
				$Hint->myerror ( "密码不能少于6位！", "2" );
				die ();
			}
			$users = $usersmodel->select ();
			for($i = 0; $i < sizeof ( $users ); $i ++) {
				if ($users [$i] ['stunum'] == $stunum) {
					$Hint->myerror ( "学号已存在！", "1" );
					die ();
				}
			}
			
			//
			if (preg_match ( "/[\x7f-\xff]/", $username )) {
				$Hint->myerror ( "用户名不能为中文！", "1" );
				die ();
			}
			//
			
			$date ['username'] = $username;
			$date ['pwd'] = md5 ( $password1 );
			$date ['realname'] = $realname;
			$date ['stunum'] = $stunum;
			$date ['email'] = $email;
			$date ['phone'] = $phone;
			$date ['photo'] = $photoname;
			$date ['intro'] = $intro;
			$date ['role'] = '1';
			$date ['regdate'] = date ( "Y-m-d H:i:s" ); // 取当前时间
			$date ['Token'] = base64_encode ( $_POST ['password'] );
			
			$result = $usersmodel->add ( $date ); // 添加到数据库
			if ($result) {
				$Hint->mysuccee ( "注册成功！", "1", "Home/Account/Login" ); // 注册成功跳转到登录页面
				die ();
			} else {
				$Hint->myerror ( "注册失败！", "2" ); // 失败跳回上一页
				die ();
			}
		} else {
			$this->display ();
		}
	}
	*/
	// 用户注册模块
	public function Registered() {
		session ( null ); // 清空session
		if (! empty ( $_POST )) {
			session ( null ); // 清空session
			$Hint = new \Operation\Controller\HintController (); // 实例化Hint
			$usersmodel = M ( 'users' ); // 实例化users
			
			$image = new \Think\Image (); // 实例化Image
			
			if (null != $_FILES ['photo'] ['name']) { // 判断文件是否被修改，如果为空则不调用upload方法
				$info = $Hint->upload ( 'photo' ); // 调用upload方法
				$photoname = $info ['photo'] ['savepath'] . $info ['photo'] ['savename']; // 存储头像的子目录和名字
				$image->open ( './Public/UPLOADS/photo/' . "$photoname" ); // 打开原头像
				$image->thumb ( 200, 200, \Think\Image::IMAGE_THUMB_FIXED )->save ( './Public/UPLOADS/photo/' . "$photoname" ); // 按照原图的比例生成一个最大为200*200的缩略图并保存
			} else {
				$photoname = $Hint->randPhoto (); // 随机给个头像
			}
			
			$username = $_POST ['username']; // 取出账户名
			$password1 = $_POST ['password']; // 取出密码
			$password2 = $_POST ['password_ok']; // 取出确认密码
			$stunum = $_POST ['stunum']; // 学号
			$realname = $_POST ['realname']; // 真实姓名
			$email = $_POST ['email']; // email
			$phone = $_POST ['phone']; // 电话号
			$intro = $_POST ['intro']; // 个人介绍
			
			if ($password1 !== $password2) {
				$Hint->myerror ( "两次密码输入不一致！", "2" );
				die ();
			}
			if (false == (strlen ( $password1 ) > 5 && strlen ( $username ) > 2)) { // 验证账户和密码是否过于简单
				$Hint->myerror ( "密码不能少于6位！", "2" );
				die ();
			}
			$users = $usersmodel->select ();
			for($i = 0; $i < sizeof ( $users ); $i ++) {
				if ($users [$i] ['stunum'] == $stunum) {
					$Hint->myerror ( "学号已存在！", "1" );
					die ();
				}
			}
			
			//
			if (preg_match ( "/[\x7f-\xff]/", $username )) {
				$Hint->myerror ( "用户名不能为中文！", "1" );
				die ();
			}
			//
			
			$date ['username'] = $username;
			$date ['pwd'] = md5 ( $password1 );
			$date ['realname'] = $realname;
			$date ['stunum'] = $stunum;
			$data['is_teacher'] =I('post.identify');//判断用户身份，0为学生，1为教师
			var_dump($data['is_teacher'] );

			$date ['email'] = $email;
			$date ['phone'] = $phone;
			$date ['photo'] = $photoname;
			$date ['intro'] = $intro;
			$date ['role'] = '1';
			$date ['regdate'] = date ( "Y-m-d H:i:s" ); // 取当前时间
			$date ['Token'] = base64_encode ( $_POST ['password'] );
			
			$result = $usersmodel->add ( $date ); // 添加到数据库
			if ($result) {
				$Hint->mysuccee ( "注册成功！", "1", "Home/Account/Login" ); // 注册成功跳转到登录页面
				die ();
			} else {
				$Hint->myerror ( "注册失败！", "2" ); // 失败跳回上一页
				die ();
			}
		} else {
			$this->display ();
		}
	}
	
	// 用户登陆模块 -- 陈柏村
	public function Login() {
		session ( null );
		$Hint = new \Operation\Controller\HintController ();
		
		// 判断是否有数据POST过来
		if (! empty ( $_POST )) {
			
			// show_bug($_POST);
			
			// 实例化Users对象
			$Users = new \Model\usersModel ();
			
			// 检查用户名和密码是否存在
			$userName = I ( "post.username" );
			$passWrod = I ( "post.password" );
			
			$userInfo = $Users->checkNamePwd ( $userName, md5 ( $passWrod ) );
			
			// 用户名或者密码不存在进行相关提示
			if ($userInfo === false) {
				$Hint->myerror ( "用户名或密码错误!请返回重新输入!" );
			} else {
				
				// 验证通过后 写入session 并跳转页面
				// session userType 1(学生)2（教师）3（管理员）
				
				session ( 'userType', $userInfo ['role'] );
				session ( 'userUsername', $userInfo ['username'] );
				session ( 'userRealname', $userInfo ['realname'] );
				session ( 'userUid', $userInfo ['uid'] );
				session ( 'userPhoto', $userInfo ['photo'] );
				
				// 是否勾选remember,记住用户名
				
				if ($_POST ['remember'] == on) {
					// 写入cookie
					cookie ( username, $userInfo ['username'] );
					
					cookie ( password, $_POST ['password'] );
				}
				
				switch ($userInfo ['role']) {
					
					case 1 :
						
						// 用户页面
						$studentUrl = DOMAIN_NAME . 'Home/Index/index';
						header ( "Location: $studentUrl" );
						
						die ();
					case 2 :
						
						// 教师页面
						die ();
					case 3 :
						
						// 管理员页面
						
						$adminUrl = DOMAIN_NAME . 'Admin/Index/index';
						header ( "Location: $adminUrl" );
						die ();
					default :
						
						// 非法操作!
						die ();
				}
				
				// $this->redirect('Home/HomeworkList/homeWorkList');
			}
		} else {
			
			$this->display ();
		}
	}
}
